// 操作数库的对象  db
// 数据库：blog_database
// 数据表：pre_user

// SELECT  字段
// FROM  数据表
// WHERE  条件
// INSERT  INTO 插入
// INTO   数据表
// UPDATE   数据表  更新
// DELETE   删除  
// DELETE FROM 数据表

const db = require("../common/db/index")
const Jwt = require("../common/jwt")
const aes = require("../common/aes")


module.exports = {
    list() {
        return new Promise(async (resolve, reject) => {
            const rows = await db.query(`SELECT count(*) as total FROM pre_user`);
            const sql = 'SELECT username , gender FROM pre_user'
            await db.query(sql)
                .then(
                    result => {
                        resolve({
                            total: rows[0].total,
                            result,
                            msg: "获取用户列表成功",
                            code: 200
                        })
                    },
                    err => {
                        reject({
                            err,
                            msg: "获取数据失败",
                            code: -1
                        })
                    }
                )
        })
    },
    // 注册的操作
    register(account, password, username, createAt, gender = "", imgUrl = "", role = '0', tag = '') {
        return new Promise(async (resolve, reject) => {
            const sql = 'SELECT account FROM pre_user WHERE account = ?';
            // rows 数组
            // console.log(rows)
            const rows = await db.query(sql, [account]);
            if (rows.length == 0) {
                // 未注册
                // 对密码进行加密
                let pwd = aes.aesEncrypt(password)
                // 编写sql语句（插入数据）
                const sql = 'INSERT INTO pre_user (account, password, username,createAt, gender, imgUrl, role,tag) VALUES (?, ?, ?,?,?, ?,?,?)';
                db.query(sql, [account, pwd, username, createAt, gender, imgUrl, role, tag])
                    .then(
                        result => {
                            resolve({
                                result,
                                msg: "恭喜你,注册成功",
                                code: 200
                            })
                        },
                        err => {
                            reject(err)
                        }
                    )
            }
            else {
                // 已注册
                resolve({
                    msg: "该账号已经存在",
                    code: 1
                })
            }
        })
    },

    // 登录的操作
    login(account, password) {
        return new Promise(async (resolve, reject) => {
            // 先根据明文的账户检索数据库用户表
            const sql = 'SELECT account,username,gender,imgUrl,createAt, password,tag, id FROM pre_user WHERE account = ?';
            db.query(sql, [account])
                .then(
                    result => {
                        // result 数组
                        if (result.length == 0) {
                            resolve({
                                msg: "不存在该用户"
                            })
                        }
                        else {
                            // 解密操作
                            // 通过布尔值 判断密码是否一致                                
                            // let isLogin = aes.aesDecrypt(明文（用户提交的参数）, 加密的（数据表中的字段）)    
                            let isLogin = aes.aesDecrypt(password, result[0].password)
                            // console.log(1,result);
                            // console.log(2,isLogin);// true  数据匹配 ;  false 数据不匹配
                            if (isLogin) {
                                let user = result[0];//用户信息
                                // 用户id
                                let token = new Jwt(user.id).getToken();
                                resolve({
                                    id: user.id,
                                    username: user.username,
                                    account: user.account,
                                    password: user.password,
                                    gender: user.gender,
                                    createAt: user.createAt,
                                    imgUrl: user.imgUrl,
                                    token: token,
                                    tag: user.tag,
                                    msg: "登录成功",
                                    code: 200
                                })
                            }
                            else {
                                resolve({
                                    msg: "登录失败",
                                    code: -1
                                })
                            }
                        }

                    },
                    err => {
                        reject(err)
                    }
                )
        })

        // rows 数组
        // console.log(rows)
        // const rows = await db.query(sql, [account]);

    },

    // 删除的操作
    remove(id) {
        return new Promise((resolve, reject) => {
            // do something ... 
            // 编写sql语句（更新数据）
            // ? 占位符  和[ ]的参数顺序是一一对应的
            const sql = 'DELETE FROM pre_user WHERE id = ?';
            db.query(sql, [id])
                .then(
                    result => {
                        resolve({
                            msg: "删除成功",
                            code: 200,
                            result
                        })
                    },
                    err => {
                        reject({
                            err,
                            code: -1,
                            msg: "删除失败"
                        })
                    }
                )

        })
    },

    // 用户列表
    items(page_num, page_size) {
        return new Promise(async (resolve, reject) => {
            // 编写sql语句 （查询语句）
            // 页码：第几页
            // 数量: 每一页的数量
            // 编写sql语句（更新数据）
            // ? 占位符  和[ ]的参数顺序是一一对应的
            const rows = await db.query(`SELECT count(*) as total FROM pre_user`);
            // 换种写法
            // 写法2：
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = `select * from pre_user limit ${page_num2} , ${page_size2}`
            await db.query(sql)
                .then(
                    data => {
                        resolve({
                            total: rows[0].total,
                            data,
                            msg: "获取用户列表",
                            code: 200
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },

    // 用户修改 用户名、性别、头像、个性签名 
    modify(username, gender, imgUrl, tag, id) {
        return new Promise((resolve, reject) => {
            // 编写sql语句（更新数据）
            const sql = 'UPDATE pre_user SET username = ?, gender = ? , imgUrl = ?,tag=? WHERE id = ?';
            db.query(sql, [username, gender, imgUrl, tag, id])
                .then(
                    result => {
                        resolve({
                            code: 200,
                            msg: "修改用户信息成功",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "修改用户信息失败",
                            err
                        })
                    }
                )

        })
    },
    // 用户修改密码(用户修改)
    modifyPassword(password, id) {
        return new Promise((resolve, reject) => {
            // 密码加密
            let newPassword = aes.aesEncrypt(password);
            // 密码修改
            const sql = 'UPDATE pre_user SET password = ? WHERE id = ?';
            db.query(sql, [newPassword, id])
                .then(
                    result => {
                        resolve({
                            code: 200,
                            msg: "修改密码成功",
                            result
                        })
                    }, err => {
                        reject({
                            code: -1,
                            msg: "修改密码失败",
                            err
                        })
                    }
                )
        })
    },

    // 搜索用户
    search(keyword) {
        return new Promise((resolve, reject) => {
            // 编写sql语句（模糊查询）
            const sql = 'SELECT id, account,username,gender,imgUrl,createAt,tag FROM pre_user WHERE account LIKE ? or username LIKE ? ';
            db.query(sql, [`%${keyword}%`, `%${keyword}%`])
                .then(
                    result => {
                        if (result.length > 0) {
                            resolve({
                                code: 200,
                                msg: "搜索用户成功",
                                result
                            })
                        } else {
                            resolve({
                                code: -1,
                                msg: "没有搜索到用户",
                                result
                            })
                        }
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "搜索用户失败",
                            err
                        })
                    }
                )
        })
    },

    // 查看用户详情
    detail(id) {
        return new Promise((resolve, reject) => {
            // 编写sql语句 （查询语句）
            const sql = 'SELECT * FROM pre_user WHERE id = ?';
            // 通过query方法执行sql语句
            db.query(sql, [Number(id)])
                .then(
                    result => {
                        resolve({
                            code: 200,
                            msg: "用户详情查询成功",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "用户详情查询失败",
                            err
                        })
                    }
                )

        })
    },

}